from django.shortcuts import render
from django.shortcuts import redirect
from django.conf import settings
from .models import User,ConfirmString
from .forms import UserForm,RegisterForm
# Create your views here.
import hashlib
import datetime
import pytz

def hash_code(s,salt='mysite'):#add a little salt
    h=hashlib.sha3_256()
    s += salt
    h.update(s.encode())
    return h.hexdigest()


def make_confirm_string(user):
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    code=hash_code(user.name, now)
    ConfirmString.objects.create(code=code,user=user)
    return code


def send_email(email, code):
    from django.core.mail import EmailMultiAlternatives
    subject = '来自www.liujiangblog.com的注册确认邮件'
    text_content = '''
    感谢注册www.liujiangblog.com，专注于Python、Django和机器学习技术的分享！\
    如果你看到这条消息，说明你的邮箱服务器不提供HTML链接功能，请联系管理员！
    '''
    html_content = '''
    <p>感谢注册<a href="http://{}/confirm/?code={}" target=blank>www.liujiangblog.com</a>，\
    这里是刘江的博客和教程站点，专注于Python、Django和机器学习技术的分享！</p>
    <p>请点击站点链接完成注册确认！</p>
    <p>此链接有效期为{}天！</p>
    '''.format('127.0.0.1:8000', code, settings.CONFIRM_DAYS)
    print(email,code)
    msg=EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER,[email])
    msg.attach_alternative(html_content, 'text/html')
    msg.send()
    print('send ok')


def index(request):
    # pass
    if not request.session.get('is_login', None):
        redirect("/login/")
    return render(request, 'login/index.html')


def login(request):
    if request.session.get("is_login",None):
        return redirect('/index/')
    if request.method == "POST":
        login_form=UserForm(request.POST)
        message = 'please check you input'
        if login_form.is_valid():
            #确保用户名和密码不为空
            #用户字符合法性验证
            #密码长度验证
            #更多的其它验证
            username = login_form.cleaned_data.get("username")
            password = login_form.cleaned_data.get("password")
            try:
                user = User.objects.get(name=username)
            except:
                message = 'user is no exists.'
                return render(request, 'login/login.html', locals())
            if not user.has_confirmed:
                message = 'user email is not confirm'
                return render(request, 'login/login.html', locals())
            if user.password == hash_code(password):
                # print(len(user.password))
                request.session['is_login'] = True
                request.session['user_id'] = user.id
                request.session['username'] = user.name
                return redirect('/index/')
            else:
                message = 'password is error'
                return render(request, 'login/login.html', locals())
        else:
            return render(request, 'login/login.html', locals())
    login_form = UserForm()
    return render(request, 'login/login.html', locals())


def register(request):
    if request.session.get('is_login', None):
        redirect("/index/")
    if request.method == 'POST':
        register_form = RegisterForm(request._post)
        message = 'plese check you input'
        if register_form.is_valid():
            username = register_form.cleaned_data.get('username')
            password1 = register_form.cleaned_data.get('password1')
            password2 = register_form.cleaned_data.get('password2')
            email = register_form.cleaned_data.get('email')
            sex = register_form.cleaned_data.get('sex')
            if password1 != password2:
                message = 'twice password is not same.'
                return render(request, 'login/register.html', locals())
            else:
                same_name_user = User.objects.filter(name=username)
                if same_name_user:
                    message = 'username has existed.'
                    return render(request, 'login/register.html', locals())
                same_email_user = User.objects.filter(email=email)
                if same_email_user:
                    message = 'the email has existed.'
                    return render(request, 'login/register.html', locals())
                new_user = User()
                new_user.name = username
                new_user.password = hash_code(password1)
                new_user.email = email
                new_user.sex = sex
                new_user.save()
                code = make_confirm_string(new_user)
                send_email(email, code)
                message = '请前往邮箱进行确认'
                return render(request, 'login/confirm.html',locals())
        else:
            return render(request, 'login/register.html', locals())
    register_form = RegisterForm()
    return render(request, 'login/register.html', locals())


def logout(request):
    # pass
    if not request.session.get('is_login',None):
        return redirect("/login/")
    request.session.flush()
    return redirect("/login/")


def user_confirm(request):
    code = request.GET.get("code",None)
    message = ''
    try:
        confirm = ConfirmString.objects.get(code=code)
    except:
        message = '无效的确认请求'
        return render(request, 'login/confirm.html', locals())
    c_time = confirm.c_time
    now = datetime.datetime.now().replace(tzinfo=pytz.timezone("UTC"))
    if now > c_time + datetime.timedelta(settings.CONFIRM_DAYS):
        confirm.user.delete()
        message = '验证码已过期，请重新注册。'
        return render(request, 'login/login.html', locals())
    else:
        confirm.user.has_confirmed = True
        confirm.user.save()
        confirm.delete()
        message = '感谢确认，请使用帐户登录'
        return render(request, 'login/confirm.html', locals())
